package com.TripMate.system.controller;

import com.TripMate.system.annotation.AuthCheck;
import com.TripMate.system.common.BaseResponse;
import com.TripMate.system.common.DeleteRequest;
import com.TripMate.system.common.ErrorCode;
import com.TripMate.system.common.ResultUtils;
import com.TripMate.system.constant.UserConstant;
import com.TripMate.system.exception.BusinessException;
import com.TripMate.system.exception.ThrowUtils;
import com.TripMate.system.model.dto.favorites.FavoritesQueryRequest;
import com.TripMate.system.model.dto.trips.TripsAddRequest;
import com.TripMate.system.model.dto.trips.TripsQueryRequest;
import com.TripMate.system.model.dto.trips.TripsUpdateRequest;
import com.TripMate.system.model.entity.Trips;
import com.TripMate.system.model.entity.User;
import com.TripMate.system.model.vo.FavoritesByTripVO;
import com.TripMate.system.model.vo.LoginUserVO;
import com.TripMate.system.model.vo.TripsVO;
import com.TripMate.system.model.vo.TripsVOByMy;
import com.TripMate.system.service.TripsService;
import com.TripMate.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户行程接口
 *
 * @author dongyanmian
 */
@RestController
@RequestMapping("/trips")
@Slf4j
@Api(tags = "用户行程接口")
public class TripsController {

    @Resource
    private UserService userService;

    @Resource
    private TripsService tripsService;

    // region 增删改查

    /**
     * 创建用户行程接口
     *
     * @param tripsAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建用户行程接口")
    public BaseResponse<Integer> addTrips(@RequestBody TripsAddRequest tripsAddRequest, HttpServletRequest request) {
        if (tripsAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Trips trips = new Trips();
        BeanUtils.copyProperties(tripsAddRequest, trips);
        Long id = userService.getLoginUser(request).getId();
        trips.setUserId(id);
        boolean result = tripsService.save(trips);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建行程失败");
        return ResultUtils.success(trips.getId());
    }

    /**
     * 删除用户行程
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除用户行程")
    public BaseResponse<Boolean> deleteTrips(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userService.getLoginUser(request).getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = deleteRequest.getId();
        boolean result = tripsService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除行程失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新用户行程
     *
     * @param tripsUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新用户行程")
    public BaseResponse<TripsVOByMy> updateTrips(@RequestBody TripsUpdateRequest tripsUpdateRequest, HttpServletRequest request) {
        // 检查请求参数是否为空或无效
        if (tripsUpdateRequest == null || tripsUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的请求参数");
        }

        // 获取当前登录用户的ID
        Long userId = userService.getLoginUser(request).getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的用户信息");
        }

        // 查询行程记录
        QueryWrapper<Trips> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", tripsUpdateRequest.getId());
        Trips existingTrip = tripsService.getOne(queryWrapper);

        // 检查行程是否存在且用户是否有权限更新
        if (existingTrip == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "行程记录不存在");
        }
        if (!userId.equals(existingTrip.getUserId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限更新行程");
        }

        // 将请求参数复制到行程对象
        Trips updatedTrip = new Trips();
        BeanUtils.copyProperties(tripsUpdateRequest, updatedTrip);

        // 更新行程记录
        boolean result = tripsService.updateById(updatedTrip);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新行程失败");
        }

        // 构建返回结果
        TripsVOByMy tripsUpdateVO = new TripsVOByMy();
        BeanUtils.copyProperties(updatedTrip, tripsUpdateVO);

        // 返回成功响应
        return ResultUtils.success(tripsUpdateVO);
    }

    /**
     * 分页获取自己的行程列表
     *
     * @param tripsQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/all/my")
    @ApiOperation("分页获取自己的行程列表")
    public BaseResponse<Page<TripsVO>> listTripsByMy(@RequestBody TripsQueryRequest tripsQueryRequest, HttpServletRequest request) {
        long current = tripsQueryRequest.getCurrent() == 0 ? 1 : tripsQueryRequest.getCurrent();
        long size = tripsQueryRequest.getPageSize() == 0 ? 10 : tripsQueryRequest.getPageSize();

        Long userId = userService.getLoginUser(request).getId();
        Page<TripsVO> pageParam = new Page<>(current, size);
        Page<TripsVO> tripsVOPage = tripsService.getQueryByMy(pageParam, tripsQueryRequest, userId);
        if (tripsVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
        return ResultUtils.success(tripsVOPage);
    }

    /**
     * 根据 id 获取自己得行程
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/list/id")
    @ApiOperation("根据 id 获取自己得行程")
    public BaseResponse<TripsVO> listTripsByMy(Integer id, HttpServletRequest request) {

        TripsVO tripsVOPage = tripsService.getQueryById(id);
        if (tripsVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "根据 id 查询失败");
        }
        return ResultUtils.success(tripsVOPage);
    }

    /**
     * 分页获取全部用户收藏（仅管理员）
     *
     * @param tripsQueryRequest
     * @return
     */
    @PostMapping("/list/all/trip")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("分页获取全部用户的行程（仅管理员）")
    public BaseResponse<Page<TripsVO>> listByAll(@RequestBody TripsQueryRequest tripsQueryRequest) {
        long current = tripsQueryRequest.getCurrent() == 0 ? 1 : tripsQueryRequest.getCurrent();
        long size = tripsQueryRequest.getPageSize() == 0 ? 10 : tripsQueryRequest.getPageSize();

        Page<TripsVO> pageParam = new Page<>(current, size);
        Page<TripsVO> favoritesVOPage = tripsService.getlistByAll(pageParam, tripsQueryRequest);
        if (favoritesVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询全部用户的行程收藏失败");
        }

        return ResultUtils.success(favoritesVOPage);
    }

    // endregion
}
